import sys
import os
from PyQt5.QtCore import pyqtSignal, QThread, QTimer, QUrl
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply, QHttpMultiPart, QHttpPart
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QProgressBar, QDesktopWidget, QHBoxLayout, QFrame, QTextEdit, QLabel
from connection import ssh_tunnel
import connection
import requests

class SshTunnelThread(QThread):
    statusChanged = pyqtSignal(int)

    def run(self):
        try:
            # global ssh_tunnel_status
            print("SSH tunnel")
            print(f"线程开始运行，当前状态：{connection.ssh_tunnel_status}")
            self.statusChanged.emit(connection.ssh_tunnel_status)
            ssh_tunnel()  # ssh_tunnel函数持续执行的

        except Exception as e:
            print(f"线程运行中发生错误：{e}")
            self.statusChanged.emit(-1)  # 发送错误状态


class MainWindow(QMainWindow):

    #确认当前连接状态
    isLinked: bool
    def __init__(self):
        super().__init__()
        self.isLinked = False
        self.initUI()
        self.sshThread = SshTunnelThread()
        self.sshThread.statusChanged.connect(self.update_ui)
        # 创建 QTimer 实例
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.check_status)
        self.timer.start(1000)  # 每秒检查一次

    #建立SSH连接
    def connectSSH(self):
        print("Connecting to SSH")
        if not self.sshThread.isRunning():
            self.sshThread.start()
        else:
            print("线程已经在运行中")

    def update_ui(self, status):
        print("SSH隧道状态:", status)

        if status == 1:
            print("SSH隧道已建立，继续执行其他操作。")

            self.tempStatus.setText("已连接")
            self.statusText.setPlaceholderText("等待接收")
            self.isLinked = True
            self.receiveButton.setEnabled(self.isLinked)
        elif status == 2:
            print("SSH隧道建立失败")

            self.tempStatus.setText("连接失败")
            self.isLinked = False
            self.receiveButton.setEnabled(self.isLinked)
        else:
            print("SSH隧道已关闭。")

            self.tempStatus.setText("未连接")
            self.isLinked = False
            self.receiveButton.setEnabled(self.isLinked)

    #超时处理
    def handle_timeout(self):
        print("SSH隧道建立超时，操作已终止。")
        self.tempStatus.setText("连接超时")
        if self.sshThread.isRunning():
            self.sshThread.terminate()  # 尝试终止线程
        self.sshThread.wait()  # 等待线程终止

    #监听
    def check_status(self):
        status = connection.ssh_tunnel_status
        self.update_ui(status)


    #接收文件
    def receiveFile(self):
        # 指定路径
        path = "D:/火电巡检系统/103"

        # 遍历文件夹
        for folder in os.listdir(path):
            try:
                catalog = int(folder)
                inspectionGroupId = catalog // 100
                inspectionDetailId = catalog % 100
                print("inspectionGroupId:", inspectionGroupId)
                print("inspectionDetailId:", inspectionDetailId)

            except ValueError:
                print(f"无法将文件夹名‘{folder}’转换为整数")
                continue

            # 构建完整的 URL
            url = f"http://localhost:8090/api/inspection/submit/{inspectionGroupId}/{inspectionDetailId}"

            # 创建多部分表单数据
            files = []
            folders = os.path.join(path, folder)

            # 添加图像文件
            for filename in os.listdir(folders):
                if filename.endswith('.jpg'):
                    image_path = os.path.join(folders, filename)
                    with open(image_path, 'rb') as f:
                        files.append(('imageList', (filename, f.read(), 'image/jpeg')))  # 使用 'imageList'

            # 添加音频和 JSON 文件
            for filename in os.listdir(folders):
                if filename.endswith('.mp3'):
                    radio_path = os.path.join(folders, filename)
                    with open(radio_path, 'rb') as f:
                        files.append(('cheatMsg', (filename, f.read(), 'audio/mpeg')))
                elif filename.endswith('.json'):
                    data_path = os.path.join(folders, filename)
                    with open(data_path, 'rb') as f:
                        files.append(('dataListJson', (filename, f.read(), 'application/json')))

            # 发送请求
            response = requests.post(url, files=files)

            # 处理响应
            if response.status_code == 200:
                print("请求成功:", response.json())  # 或者根据需要处理响应内容
            else:
                print("请求失败，状态码:", response.status_code, response.text)

    def handleResponse(self, reply):
        error = reply.error()
        if error == QNetworkReply.NoError:
            print("请求成功：")
            response = reply.readAll().data().decode()
            print(response)
            self.statusText.setText(response)
            self.progressBar.setValue(self.progressBar.maximum())

        else:
            print("请求失败：", reply.errorString())
            self.progressBar.setValue(0)
        # 设置进度条最大值
        reply.deleteLater()

    def updateProgress(self, bytesReceived, totalBytes):
        self.progressBar.setMaximum(totalBytes)
        self.progressBar.setValue(bytesReceived)


    def initUI(self):
        self.setWindowTitle('连接与接收')
        # 获取屏幕尺寸
        # 获取屏幕尺寸
        desktop = QDesktopWidget()
        screen_width = desktop.screenGeometry().width()
        screen_height = desktop.screenGeometry().height()

        # 获取窗口尺寸
        window_width = 800  # 设置一个较大的窗口宽度以便于按钮水平分布
        window_height = 500  # 设置一个较小的窗口高度

        # 计算窗口起始坐标
        x = (screen_width - window_width) // 2
        y = (screen_height - window_height) // 2

        # 设置窗口位置
        self.setGeometry(x, y, window_width, window_height)

        # 创建左侧布局
        leftLayout = QVBoxLayout()
        self.connectButton = QPushButton('连接', self)
        self.connectButton.clicked.connect(self.connectSSH)
        self.statusLabel = QLabel("状态")
        self.tempStatus = QLabel("未连接")

        statusLayout = QHBoxLayout()
        statusLayout.addWidget(self.statusLabel)
        statusLayout.addWidget(self.tempStatus)

        self.statusText = QTextEdit(self)
        self.statusText.setReadOnly(True)
        self.statusText.setPlaceholderText("当前未连接")
        leftLayout.addWidget(self.connectButton)


        leftLayout.addLayout(statusLayout)
        leftLayout.addWidget(self.statusText)

        # 创建右侧布局
        rightLayout = QVBoxLayout()
        self.receiveButton = QPushButton('接收', self)
        self.receiveButton.setEnabled(self.isLinked)
        self.receiveButton.clicked.connect(self.receiveFile)
        self.progressBar = QProgressBar(self)
        self.progressBar.hide()  # 初始时隐藏进度条
        rightLayout.addWidget(self.receiveButton)
        rightLayout.addWidget(self.progressBar)

        # 创建中间分割线
        divider = QFrame(self)
        divider.setFrameShape(QFrame.VLine)
        divider.setLineWidth(1)

        # 创建主布局
        mainLayout = QHBoxLayout()
        mainLayout.addLayout(leftLayout)
        mainLayout.addWidget(divider)
        mainLayout.addLayout(rightLayout)

        # 设置中心窗口
        centralWidget = QWidget()
        centralWidget.setLayout(mainLayout)
        self.setCentralWidget(centralWidget)


        self.manager = QNetworkAccessManager()
        self.manager.finished.connect(self.handleResponse)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit(app.exec_())


